package com.zycoin.nio;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;

/**
 * @author zhongyicheng
 * create date 2018/1/11.
 */
public class Acceptor implements Runnable,Runner {
    private ServerSocketChannel serverSocket;
    private Selector[] selectors = new Selector[3];
    int next = 0;

    public Acceptor(ServerSocketChannel serverSocket) {
        this.serverSocket = serverSocket;
        SelectorProvider sp = SelectorProvider.provider();
        try {
            for (int i = 0; i < 3; i++) {
                selectors[i] = sp.openSelector();
                new Thread(new Dispatch(selectors[i])).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            SocketChannel socketChannel = serverSocket.accept();
            if (socketChannel != null)
                new Handler(selectors[next], socketChannel);
            if (++next == selectors.length) next = 0;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
